import os
import shutil
import time
import logging
from datetime import datetime, timedelta
from werkzeug.utils import secure_filename
import uuid

def get_safe_filename(filename):
    """
    获取安全的文件名
    
    Args:
        filename (str): 原始文件名
        
    Returns:
        str: 安全的文件名
    """
    # 使用 secure_filename 确保文件名安全
    safe_name = secure_filename(filename)
    
    # 如果没有扩展名，添加默认扩展名
    if '.' not in safe_name:
        safe_name += '.mp4'
    
    # 添加唯一标识符避免文件名冲突
    name, ext = os.path.splitext(safe_name)
    unique_name = f"{name}_{uuid.uuid4().hex[:8]}{ext}"
    
    return unique_name

def cleanup_old_files(directory, max_age_hours=24):
    """
    清理指定目录中的旧文件
    
    Args:
        directory (str): 要清理的目录
        max_age_hours (int): 文件最大保留时间（小时）
    """
    try:
        if not os.path.exists(directory):
            return
        
        current_time = time.time()
        max_age_seconds = max_age_hours * 3600
        
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            
            # 检查文件年龄
            if os.path.isfile(file_path):
                file_age = current_time - os.path.getmtime(file_path)
                
                if file_age > max_age_seconds:
                    try:
                        os.remove(file_path)
                        logging.info(f"已删除旧文件: {file_path}")
                    except OSError as e:
                        logging.error(f"删除文件失败 {file_path}: {e}")
            
            # 递归清理子目录
            elif os.path.isdir(file_path):
                cleanup_old_files(file_path, max_age_hours)
                
    except Exception as e:
        logging.error(f"清理文件时出错: {e}")

def get_file_size_mb(file_path):
    """
    获取文件大小（MB）
    
    Args:
        file_path (str): 文件路径
        
    Returns:
        float: 文件大小（MB）
    """
    try:
        size_bytes = os.path.getsize(file_path)
        return size_bytes / (1024 * 1024)
    except OSError:
        return 0

def format_duration(seconds):
    """
    格式化持续时间
    
    Args:
        seconds (float): 秒数
        
    Returns:
        str: 格式化的时间字符串
    """
    if seconds < 60:
        return f"{seconds:.1f}秒"
    elif seconds < 3600:
        minutes = seconds / 60
        return f"{minutes:.1f}分钟"
    else:
        hours = seconds / 3600
        return f"{hours:.1f}小时"

def validate_file_extension(filename, allowed_extensions):
    """
    验证文件扩展名
    
    Args:
        filename (str): 文件名
        allowed_extensions (set): 允许的扩展名集合
        
    Returns:
        bool: 是否有效
    """
    if '.' not in filename:
        return False
    
    extension = filename.rsplit('.', 1)[1].lower()
    return extension in allowed_extensions

def create_temp_directory(base_dir, prefix="temp_"):
    """
    创建临时目录
    
    Args:
        base_dir (str): 基础目录
        prefix (str): 目录名前缀
        
    Returns:
        str: 临时目录路径
    """
    temp_dir = os.path.join(base_dir, f"{prefix}{uuid.uuid4().hex[:8]}")
    os.makedirs(temp_dir, exist_ok=True)
    return temp_dir

def cleanup_temp_directory(temp_dir):
    """
    清理临时目录
    
    Args:
        temp_dir (str): 临时目录路径
    """
    try:
        if os.path.exists(temp_dir):
            shutil.rmtree(temp_dir)
            logging.info(f"已清理临时目录: {temp_dir}")
    except Exception as e:
        logging.error(f"清理临时目录失败 {temp_dir}: {e}")

def get_video_thumbnail(video_path, output_path, time_position="00:00:05"):
    """
    生成视频缩略图
    
    Args:
        video_path (str): 视频文件路径
        output_path (str): 输出缩略图路径
        time_position (str): 截图时间位置
        
    Returns:
        bool: 是否成功
    """
    try:
        import ffmpeg
        
        stream = ffmpeg.input(video_path, ss=time_position)
        stream = ffmpeg.output(stream, output_path, vframes=1, vf='scale=320:-1')
        ffmpeg.run(stream, overwrite_output=True, quiet=True)
        
        return os.path.exists(output_path)
    except Exception as e:
        logging.error(f"生成缩略图失败: {e}")
        return False

def check_ffmpeg_available():
    """
    检查 FFmpeg 是否可用
    
    Returns:
        bool: 是否可用
    """
    try:
        import subprocess
        result = subprocess.run(['ffmpeg', '-version'], 
                              capture_output=True, text=True, timeout=10)
        return result.returncode == 0
    except Exception:
        return False

def get_system_info():
    """
    获取系统信息
    
    Returns:
        dict: 系统信息
    """
    import platform
    import psutil
    
    try:
        return {
            'platform': platform.system(),
            'platform_version': platform.version(),
            'python_version': platform.python_version(),
            'cpu_count': psutil.cpu_count(),
            'memory_total_gb': round(psutil.virtual_memory().total / (1024**3), 2),
            'disk_usage_percent': psutil.disk_usage('/').percent,
            'ffmpeg_available': check_ffmpeg_available()
        }
    except ImportError:
        return {
            'platform': platform.system(),
            'platform_version': platform.version(),
            'python_version': platform.python_version(),
            'ffmpeg_available': check_ffmpeg_available()
        }

def setup_logging(log_level='INFO', log_file=None):
    """
    设置日志配置
    
    Args:
        log_level (str): 日志级别
        log_file (str): 日志文件路径
    """
    log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    
    if log_file:
        logging.basicConfig(
            level=getattr(logging, log_level.upper()),
            format=log_format,
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
    else:
        logging.basicConfig(
            level=getattr(logging, log_level.upper()),
            format=log_format
        )

def get_current_app():
    """获取当前Flask应用实例"""
    from flask import current_app
    return current_app 